<template>
  <div class="demo-main" ref="demoMain">
    <canvas id="myCanvas" ref="myCanvas"></canvas>
  </div>
</template>
<script>
import * as THREE from 'three'
import {FontLoader} from 'three/examples/jsm/loaders/FontLoader.js'
import {TextGeometry} from 'three/examples/jsm/geometries/TextGeometry.js'
export default {
  data() {
    return {
      renderer: null,
      camera: null,
      scene: null,
      light: null,
      cube: null,
      geometry: null,
      material: null,
    }
  },
  mounted(){
    this.zoom()
    window.addEventListener('resize', this.zoom)
    this.renderHandle()
  },
  methods: {
    zoom(){
      this.$refs.myCanvas.width = this.$refs.demoMain.clientWidth
      this.$refs.myCanvas.height = this.$refs.demoMain.clientHeight
    },
    renderHandle(){
      this.renderer = new THREE.WebGLRenderer({
        canvas: document.getElementById('myCanvas')
      })
      this.renderer.setClearColor('#000')
      // 场景
      this.scene = new THREE.Scene()
      // 相机
      this.camera = new THREE.OrthographicCamera(-2.5, 2.5, 1.875, -1.875, 0.1, 100)
      this.camera.position.set(3, 3, 20)
      this.camera.lookAt(new THREE.Vector3(2, 0, 0)) 
      this.scene.add(this.camera)

      // 添加灯光
      this.light = new THREE.DirectionalLight(0xffffff)
      this.light.position.set(10, 15, 5)
      this.scene.add(this.light)

      //物料、
      this.material = new THREE.MeshLambertMaterial({
        color: 0xffff00
      })

      let loader = new FontLoader()
      // 资源必须放在public里  否则会报错
      loader.load('/libs/helvetiker_regular.typeface.json', (font) => {
        console.log(font, this.material)
        let mesh = new THREE.Mesh(new TextGeometry('Hellow, my THREEJS', {
          font: font,
          size: 0.3,
          height: 1
        }), this.material)
        this.scene.add(mesh)
        this.renderer.render(this.scene, this.camera)
      },// onProgress回调
      function ( xhr ) {
        console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
      },

      // onError回调
      function ( err ) {
        console.log( 'An error happened', err );
      })
    }
  }
}
</script>
<style lang="less" scoped>
.demo-main{
  width: 100%;
  height: 100%
}
</style>
